package net.wanho.systemSettings.service.impl;

import net.wanho.commons.exception.DAOException;
import net.wanho.commons.exception.ServiceException;
import net.wanho.commons.service.impl.BaseServiceImpl;
import net.wanho.systemSettings.dao.MenuDAO;
import net.wanho.systemSettings.po.Menu;
import net.wanho.systemSettings.service.MenuService;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class MenuServiceImpl extends BaseServiceImpl<MenuDAO, Menu> implements MenuService {
    @Override
    public List<Menu> findByCond(Map<String, String> condMap) throws DAOException {
        //查询 所有匹配条件【模糊关键字】 包含 爸爸 + 儿子
        List<Menu> allMenuList = super.baseDAO.selectByCond(condMap);
        //如果查询不到数据  直接返回 空的集合
        if (allMenuList==null || allMenuList.isEmpty()){
            return new ArrayList<>() ;
        }
        //从所有的集合中 获得所有的父元素  java 8 语法
        List<Menu> parentMenuList = allMenuList.stream().filter(menu -> menu.getParentMenuId().equals(0)).collect(Collectors.toList());
        //循环所有父菜单集合
        parentMenuList.forEach(parentMenu->{
            //当前集合的子元素
            List<Menu> sonMenuList = new ArrayList<>() ;
            for (Menu menu : allMenuList) {
                if (menu.getParentMenuId().equals(parentMenu.getMenuId())){
                    //儿子 菜单 的父菜单 【ManyToOne】的关系
                    menu.setParentMenu(parentMenu);
                    //当前子菜单添加到 儿子菜单集合中
                    sonMenuList.add(menu) ;
                }
            }
            //设置当前菜单的所有的子菜单
            parentMenu.setChildrenMenuList(sonMenuList);
        });
        return parentMenuList ;
    }

    @Override
    public List<Integer> findMenuIdListByPostionId(String postionId) throws ServiceException {
        Map<String,String> condMap = new HashMap<>(1) ;
        condMap.put("positionId",postionId) ;
        //查询 所有匹配条件【模糊关键字】 包含 爸爸 + 儿子
        List<Menu> allMenuList = super.baseDAO.selectByCond(condMap);
        //只需要id   [java8 写法]
        return allMenuList.stream().map(Menu::getMenuId).collect(Collectors.toList());
      /*
       List<Integer> idList = new ArrayList<>() ;
        for (Menu menu : allMenuList) {
            idList.add(menu.getMenuId()) ;
        }
        return idList;
        */
    }
}
